package com.tuling.multidatasource.core;

import com.tuling.multidatasource.dynamicdatasource.MultiDataSourceHolder;
import com.tuling.multidatasource.exception.LoadRoutingStategyUnMatch;
import com.tuling.multidatasource.exception.RoutingFiledArgsIsNull;
import com.tuling.multidatasource.support.TulingDsRoutingSetProperties;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * @Author: lijunwei
 * @Time: 2020/9/12 14:30
 */
@Slf4j
public class RoutingDsAndTbStrategy extends AbstractTulingRouting {

    @Override
    public String calDataSourceKey(String routingFieldValue,String routingField) {
        String dataSourceKey;

        Integer routingFieldHashCode = getRoutingFieldHashCode(routingField);

        //定位库的索引值
        Integer dsIndex = routingFieldHashCode %  getTulingDsRoutingSetProperties().getDataSourceNum();

        // 根据库的索引值定位数据源的key
        TulingDsRoutingSetProperties tulingDsRoutingSetProperties = getTulingDsRoutingSetProperties();
        Map<Integer, String> dataSourceKeysMapping = tulingDsRoutingSetProperties.getDataSourceKeysMapping();

        dataSourceKey = getTulingDsRoutingSetProperties().getDataSourceKeysMapping().get(dsIndex);

        // 放入线程变量
        MultiDataSourceHolder.setDataSourceHolder(dataSourceKey);

        log.info("根据路由字段:{},值:{},计算出数据库索引值:{},数据源key的值:{}", getTulingDsRoutingSetProperties().getRoutingField(),routingField,dsIndex,dataSourceKey);

        return dataSourceKey;
    }

    @Override
    public String calTableKey(String routingField) {

        Integer routingFieldHashCode = getRoutingFieldHashCode(routingField);

        Integer tableIndex = routingFieldHashCode %  getTulingDsRoutingSetProperties().getTableNum();

        String tableSuffix = getFormatTableSuffix(tableIndex);

        MultiDataSourceHolder.setTableIndexHolder(tableSuffix);

        return tableSuffix;
    }
}
